﻿using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using GBlog.Core.Data;
namespace GBlog.Core.Service.Default
{
    public class ConfigService : IConfigService
    {
        public string FilePath { get; private set; }

        public ConfigService(string FilePath)
        {
            this.FilePath = FilePath;
            Read();
        }

        public Config Current { get; private set; }

        public void Read()
        {
            var filename = "settings";
            var recordPath = Path.Combine(FilePath, "Config", filename + ".json");
            var json = File.ReadAllText(recordPath);
            Current = JsonConvert.DeserializeObject<Config>(json, new KeyValuePairConverter());
        }

        public void Save()
        {
            var filename = "settings";
            var recordPath = Path.Combine(FilePath, "Config");
            var json = JsonConvert.SerializeObject(Current, Formatting.Indented, new KeyValuePairConverter());
            if (!Directory.Exists(recordPath))
            {
                Directory.CreateDirectory(recordPath);
            }
            recordPath = Path.Combine(recordPath, filename + ".json");
            File.WriteAllText(recordPath, json);
        }


        public DateTime FileModificationTime
        {
            get
            {
                var filename = "settings";
                var recordPath = Path.Combine(FilePath, "Config", filename + ".json");
                FileInfo finfo = new FileInfo(recordPath);
                return finfo.LastWriteTime;
            }
        }
    }
}